/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 StdFailOverCoordinator.hpp. Created on: 15.09.2009 15:07:08
 */

#ifndef STDFAILOVERCOORDINATOR_HPP_
#define STDFAILOVERCOORDINATOR_HPP_

#include "smartobjects/SmartObjectsDefs.hpp"
#include "IEndpointCoordinator.hpp"
#include "ConnectionHandler.hpp"

namespace smartobjects {

class StdFailOverCoordinator : public IEndpointCoordinator {
public:
	SO_DLLPRFX static const std::string COORDINATOR_NAME;

public:
	SO_DLLPRFX StdFailOverCoordinator();
	SO_DLLPRFX virtual ~StdFailOverCoordinator();

	SO_DLLPRFX virtual const std::string& getName() ;
	SO_DLLPRFX virtual ConnectionHandler* getConnectionHandlerToSend ( IManagedConnection* ) ;

	SO_DLLPRFX virtual ManagedConnectionStatus onConnected(ConnectionHandler* ) ;
	SO_DLLPRFX virtual ManagedConnectionStatus onConnectionFailure(ConnectionHandler*, const std::string& sErrorMessage) ;
	SO_DLLPRFX virtual ManagedConnectionStatus onDisconnected(ConnectionHandler*) ;
	SO_DLLPRFX virtual ManagedConnectionStatus onRemoved(ConnectionHandler*) ;
	SO_DLLPRFX virtual bool onRestoreConnectionNeeded(ConnectionHandler*) ;

	SO_DLLPRFX virtual void setManagedConnectionFactory(IManagedConnectionFactory*) ;
	SO_DLLPRFX virtual void resetManagedConnectionFactory() ;
	SO_DLLPRFX virtual IManagedConnectionFactory* getManagedConnectionFactory() ;

protected:
	SO_DLLPRFX virtual ManagedConnectionStatus checkConnectionStatus(IManagedConnection*);
	SO_DLLPRFX virtual void insertHandler(IManagedConnection*, ConnectionHandler*);
	SO_DLLPRFX virtual void removeHandler(IManagedConnection*, ConnectionHandler*);

protected:
	IManagedConnectionFactory* m_poFactory;
	boost::recursive_mutex m_mxCoordinator;

	typedef std::set<ConnectionHandler*> Handlers;
	typedef boost::unordered_map< IManagedConnection*, Handlers> ConnectionsMap;
	ConnectionsMap m_mConnections;

	typedef boost::unordered_map< ConnectionHandler*, IManagedConnection*> HandlersMap;
	HandlersMap m_mHandlers;
};

}

#endif /* STDFAILOVERCOORDINATOR_HPP_ */
